#include "include/parser.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

static char* getNextLine(char arr[160], FILE* stream) {
    while (fgets(arr, 160, stream)) {
        if (arr[0] == '#' || !isalnum(arr[0])) {
            continue;
        } else {
            return arr;
        }
    }
    return NULL;
}


/*
 * Load fileName and return a FILE*
 */
ConfigFile* loadFile(char* fileName) {
    ConfigFile* newConfig = NULL;

    newConfig = malloc(sizeof(ConfigFile));
    if (!newConfig) {
        printf("Memory Allocation Failed in _FILE_ line: _LINE_\n");
        return NULL;
    }

    newConfig->file = fopen(fileName, "r");

	if (!newConfig->file) {
		free(newConfig);
        printf("Failed to Open File in _FILE_: _LINE_\n");
        return NULL;
	}

    return newConfig;
}

/*
 *
 */
void releaseConfig(ConfigFile** configFile) {
    
    if (!configFile) {
        return;
    }
    if ((*configFile)->file) {
        fclose((*configFile)->file);
    }
    free(*configFile);
    *configFile = NULL;
}

/*
 *
 */
int nextSet(ConfigFile* config) {
    char temp[160];
    char* pc;
    int i;

    if (!getNextLine(temp, config->file)) {
        return 0;
    }

    pc = strtok(temp,":");
    
    strncpy(config->currentParamter, pc, 80);
    
    pc = strtok(NULL,":");

    for (i=0; pc[i] != '\0'; i++) {
        if (isspace(pc[i])) {
            pc[i] = '\0';
            break;
        }
    }

    strncpy(config->currentValue, pc, 80);

    return 1;   
}
